package com.example.securitydemo2.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.securitydemo2.entity.AdminUser;
import com.example.securitydemo2.entity.Permission;
import com.example.securitydemo2.entity.Role;
import com.example.securitydemo2.mapper.AdminUserMapper;
import com.example.securitydemo2.mapper.PermissionMapper;
import com.example.securitydemo2.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username:{}",username);
        //登录时   会将请求转到此处
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();   //整合方式
        queryWrapper.eq(AdminUser::getUsername,username).last("limit 1");   //保证只能查出来一个数据
        AdminUser adminUser = adminUserMapper.selectOne(queryWrapper);
        if (adminUser == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> authorityList = new ArrayList<>();  //权限列表
        //查询角色
        List<Role> roleList = roleMapper.findRoleListByUserId(adminUser.getId());
        for (Role role : roleList) {
            authorityList.add(new MySimpleGrantedAuthority("ROLE_"+role.getRoleKeyword()));  //如果有角色   将角色关键字扔进去
            List<Permission> permissionByRole = this.permissionMapper.findPermissionByRole(role.getId()); //查询出权限列表
            for (Permission permission : permissionByRole) {
                authorityList.add(new MySimpleGrantedAuthority(permission.getPermissionKeyword(),permission.getPath())); //将权限关键字扔进去   2.和路径
            }
        }

        UserDetails userDetails = new User(username, adminUser.getPassword(), authorityList);  //用户名  密码  授权列表
        return userDetails;
    }
}
